package com.javasm.mingming.chat.service.impl;

import com.javasm.mingming.chat.Agreement;
import com.javasm.mingming.chat.service.ChatService;
import com.javasm.mingming.common.RedisKeys;
import com.javasm.mingming.common.exception.JavasmException;
import com.javasm.mingming.common.exception.JavasmExceptionEnum;
import com.javasm.mingming.socket.RoomSocket;
import com.javasm.mingming.webuser.entity.WebUser;
import com.javasm.mingming.webuser.entity.WebUserInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author javasm
 * @version 0.1
 * @className ChatServiceImpl
 * @descriptioin:
 * @date 2025/1/20 15:50
 * @since jdk11
 */
@Service("chatService")
public class ChatServiceImpl implements ChatService {
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    @Resource
    RoomSocket roomSocket;
    @Override
    public void messageSend(String roomId, String uid, String message) {
        String s = createMessage(uid, message);
        roomSocket.sendMessage(roomId,s);
    }
    public String createMessage(String uid,String message){
        //重新设计 message的格式,节省空间,表达更多的含义
        //一般来说,第一位,都设置为协议号(当前的这条消息,是什么消息)
        //当前,房间发消息,设计消息格式: 协议号,时间,uid,昵称,头像,消息内容
        //uid查询用户信息,是从Redis查询
        String key = String.format(RedisKeys.User_Uid,uid);
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null){
            throw new JavasmException(JavasmExceptionEnum.UserNotExist);
        }
        //可以查询到用户信息
        WebUser webUser = (WebUser)o;
        WebUserInfo userInfo = webUser.getUserInfo();
        if (userInfo == null){
            throw new JavasmException(JavasmExceptionEnum.UserNotExist);
        }
        //时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a");//12小时制
        String time = now.format(formatter);
        String msg = String.format("%s,%s,%s,%s,%s,%s",
                Agreement.Message,
                time,
                uid,
                userInfo.getNickname(),
                userInfo.getHeadPic(),
                message
        );
        return msg;
    }
}
